import { AIProvider } from './AIProvider';
import { OpenAIProvider, OpenAIConfig } from './OpenAIProvider';
import { WanxProvider, WanxConfig } from './WanxProvider';

export type AIProviderType = 'openai' | 'wanx';

export interface ProviderConfigs {
  openai: OpenAIConfig;
  wanx: WanxConfig;
}

export class AIProviderFactory {
  private static providers: Map<AIProviderType, AIProvider> = new Map();
  private static currentProvider: AIProviderType = 'openai';

  /**
   * 初始化所有提供商
   */
  static initialize(configs: Partial<ProviderConfigs>): void {
    // 初始化OpenAI提供商
    if (configs.openai) {
      try {
        const openaiProvider = new OpenAIProvider(configs.openai);
        this.providers.set('openai', openaiProvider);
        console.log('✅ OpenAI provider initialized successfully');
      } catch (error) {
        console.warn('⚠️ Failed to initialize OpenAI provider:', error);
      }
    }

    // 初始化万象提供商
    if (configs.wanx) {
      try {
        const wanxProvider = new WanxProvider(configs.wanx);
        this.providers.set('wanx', wanxProvider);
        console.log('✅ Wanx provider initialized successfully');
      } catch (error) {
        console.warn('⚠️ Failed to initialize Wanx provider:', error);
      }
    }

    // 设置默认提供商
    this.setDefaultProvider();
  }

  /**
   * 设置默认提供商
   */
  private static setDefaultProvider(): void {
    // 优先使用环境变量指定的提供商
    const envProvider = process.env.AI_PROVIDER as AIProviderType;
    if (envProvider && this.providers.has(envProvider) && this.providers.get(envProvider)?.isAvailable()) {
      this.currentProvider = envProvider;
      console.log(`🎯 Using ${envProvider} as default AI provider (from environment)`);
      return;
    }

    // 否则按优先级选择可用的提供商
    const priorityOrder: AIProviderType[] = ['openai', 'wanx'];
    
    for (const providerType of priorityOrder) {
      const provider = this.providers.get(providerType);
      if (provider && provider.isAvailable()) {
        this.currentProvider = providerType;
        console.log(`🎯 Using ${providerType} as default AI provider`);
        return;
      }
    }

    console.warn('⚠️ No AI providers are available');
  }

  /**
   * 获取当前提供商
   */
  static getCurrentProvider(): AIProvider | null {
    const provider = this.providers.get(this.currentProvider);
    return provider && provider.isAvailable() ? provider : null;
  }

  /**
   * 获取指定提供商
   */
  static getProvider(type: AIProviderType): AIProvider | null {
    const provider = this.providers.get(type);
    return provider && provider.isAvailable() ? provider : null;
  }

  /**
   * 切换提供商
   */
  static switchProvider(type: AIProviderType): boolean {
    const provider = this.providers.get(type);
    if (provider && provider.isAvailable()) {
      this.currentProvider = type;
      console.log(`🔄 Switched to ${type} provider`);
      return true;
    }
    
    console.warn(`⚠️ Cannot switch to ${type} provider: not available`);
    return false;
  }

  /**
   * 获取当前提供商类型
   */
  static getCurrentProviderType(): AIProviderType {
    return this.currentProvider;
  }

  /**
   * 获取所有可用提供商
   */
  static getAvailableProviders(): AIProviderType[] {
    const available: AIProviderType[] = [];
    
    for (const [type, provider] of this.providers.entries()) {
      if (provider.isAvailable()) {
        available.push(type);
      }
    }
    
    return available;
  }

  /**
   * 检查是否有可用的提供商
   */
  static hasAvailableProvider(): boolean {
    return this.getAvailableProviders().length > 0;
  }

  /**
   * 获取提供商状态信息
   */
  static getProviderStatus(): Record<AIProviderType, { available: boolean; current: boolean }> {
    const status: Record<AIProviderType, { available: boolean; current: boolean }> = {
      openai: { available: false, current: false },
      wanx: { available: false, current: false }
    };

    for (const [type, provider] of this.providers.entries()) {
      status[type as AIProviderType] = {
        available: provider.isAvailable(),
        current: type === this.currentProvider
      };
    }

    return status;
  }
}